package LeetCode.leetcode40;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public static int[] candidates = new int[]{10,1,2,7,6,1,5};
    public static final int target = 8;

    public static void main(String[] args) {
        Solution object = new Solution();
        System.out.println(object.combinationSum2(candidates,target));;
    }
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
//        System.out.println(Arrays.toString(candidates));
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[candidates.length];
        backTracking(candidates, res, path, 0, 0, target,used);
        return res;
    }

    public static void backTracking(int[] candidates, List<List<Integer>> res, List<Integer> path, int startIndex, int sum, int target,boolean[] used) {
        if (sum > target)
            return;
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false){
                continue;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            used[i] = true;
            backTracking(candidates, res, path, i + 1, sum, target,used);
            used[i] =false;
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}
